<script lang="ts">
	import type { CardInfo } from '$lib/api/proto/resource_card_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import EditorJS from '@editorjs/editorjs';

	interface Props {
		resourceId: string;
		cardInfo?: CardInfo;
		onCancel: () => void;
		onOk: () => void;
	}

	const props: Props = $props();

	let title = $state(props.cardInfo?.basicInfo?.title ?? '');
	let editor: EditorJS | null = $state(null);

	async function createCard() {
		if (editor == null || userStore.userSession == null) {
			return;
		}

		let contentData = await editor.save();

		await callApi(
			appStore.resourceCardApiClient.create({
				sessionId: userStore.userSession,
				resourceId: props.resourceId,
				basicInfo: {
					title: title,
					content: JSON.stringify(contentData)
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '创建知识卡片成功',
			keepTime: 2000
		});
	}

	async function updateCard() {
		if (props.cardInfo == undefined || editor == null || userStore.userSession == null) {
			return;
		}

		let contentData = await editor.save();

		await callApi(
			appStore.resourceCardApiClient.updateBasic({
				sessionId: userStore.userSession,
				resourceId: props.resourceId,
				cardId: props.cardInfo.cardId,
				basicInfo: {
					title: title,
					content: JSON.stringify(contentData)
				}
			}).response
		);
		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '修改知识卡片成功',
			keepTime: 2000
		});
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box flex-col space-y-4 w-[800px] max-w-none">
		<h3 class="text-lg font-bold">
			{props.cardInfo == undefined ? '创建知识卡片' : '修改知识卡片'}
		</h3>
		<label class="label w-full">
			<span class="label w-[90px] text-right inline-block pr-[10px]">标题:</span>
			<input type="text" class="input w-full" bind:value={title} />
		</label>

		<h4 class="text-base font-bold">内容</h4>
		<SimpleEditor
			sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
			data={props.cardInfo?.basicInfo?.content}
			placeholder="请输入内容"
			onInit={(tmpEditor) => (editor = tmpEditor)}
		/>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={title.trim() == '' || editor == null}
				onclick={() => {
					if (props.cardInfo == undefined) {
						createCard();
					} else {
						updateCard();
					}
				}}>{props.cardInfo == undefined ? '创建' : '修改'}</button
			>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>